<!-- 项目付款合同申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="htbh" required>
          <u--input v-model="model.htbh" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="propose" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
				<u-form-item label="申请时间" required>
				  <u--input v-model="model.createTime" disabled></u--input>
				</u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
				<u-form-item label="申请人所属团队" prop="applyTeam" required>
				  <h-select-team-input-popup
				    style="width: 100%"
				    v-model="model.applyTeam"
				    placeholder="请选择申请人所属团队"
				    :tdlx="1"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				  ></h-select-team-input-popup>
				</u-form-item>
				<u-form-item label="合同编号" prop="caId" required>
					<h-select-contract-manager-input
						v-model="model.caId"
						objectField="model.caId"
						placeholder="请选择合同编号"
						border="surround"
						:allList="true"
						:status="'2,3'"
						:muitFlag="true"
						:changeStatus="'unchanged'"
						style="width: 100%;"
						htlx="2"
						:triggerChange="true"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{color: '#B2B2B2'}"
						@input="htbhChange"
					>
					</h-select-contract-manager-input>
				</u-form-item>
        <u-form-item label="合同名称" prop="htmc" required>
          <u--input v-model="model.htmc" placeholder="请输入合同名称"></u--input>
        </u-form-item>
				<u-form-item label="费用类型" prop="feeType" required>
				  <h-select-input-tag
				    class="w-100"
				    v-model="model.feeType"
				    objectField="model.feeType"
				    placeholder="请选择费用类型"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="fee_type"
						@change="handleChangeFeeType"
				  ></h-select-input-tag>
				</u-form-item>
				<u-form-item label="是否采购类" prop="isCategoryType" required>
				  <h-select-input-tag
				    class="w-100"
				    v-model="model.isCategoryType"
				    objectField="model.isCategoryType"
				    placeholder="请选择是否采购类"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="is_category_type"
				    @change="handleChangeCategory"
				  ></h-select-input-tag>
				</u-form-item>
				<u-form-item label="变更类型" prop="bglx" required>
					<h-select-input-tag
						style="width: 100%;"
						v-model="model.bglx"
						objectField="model.bglx"
						placeholder="请选择变更类型"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						border="surround"
						dictName="pay_contract_change_type"
					></h-select-input-tag>
				</u-form-item>
        <u-form-item label="项目名称" prop="xmmc" required>
          <h-select-project-input
            :disabled="true"
            :proDisabled="true"
            :projectStatus="'2'"
						currentProjectStatus="!2"
            v-model="model.xmmc"
						objectField="model.xmmc"
						isOldSystem="!1"
            style="width: 100%"
            placeholder="请选择项目名称"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="xmmcChange"
          ></h-select-project-input>
        </u-form-item>
        <view v-if="model.isCategoryType === '1'">
          <u-form-item label="采购类型" prop="provisionType" required>
            <h-select-input-tag
              class="w-100"
              v-model="model.provisionType"
              objectField="model.provisionType"
              placeholder="请选择采购类型"
              border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
              dictName="provision_type"
							@change="handleProvisionType"
            ></h-select-input-tag>
          </u-form-item>
        </view>
        <view v-if="model.provisionType === '1'">
          <u-form-item label="关联单据" prop="calibrationId" required>
            <h-select-purchase-calibration-input-popup
              :projectId="model.xmmc"
              v-model="model.calibrationId"
              placeholder="请关联定标结果确认单"
              border="surround"
              style="width: 100%"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            />
          </u-form-item>
        </view>

        <view v-if="model.provisionType === '2'">
          <u-form-item label="关联单据" prop="purchaseApplyId" required>
            <h-select-purchase-apply-form-contract-input-popup
              v-model="model.purchaseApplyId"
              placeholder="请关联采购申请单"
              border="surround"
              style="width: 100%"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            />
          </u-form-item>
        </view>
				<view v-if="model.provisionType === '3'">
				  <u-form-item label="关联单据" prop="invitationId" required>
				    <h-select-purchase-Invitation-input-popup
				      v-model="model.invitationId"
				      placeholder="请关联招标采购申请单"
				      border="surround"
				      style="width: 100%"
				      suffixIcon="arrow-down-fill"
				      :suffixIconStyle="{ color: '#B2B2B2' }"
				    />
				  </u-form-item>
				</view>
        <u-form-item :label="model.feeType=='2'?'费用所属团队':'经营团队'" prop="jytd" required>
          <h-select-team-input-popup
					  @change="changeBusinessCompany"
            style="width: 100%"
            v-model="model.jytd"
            placeholder="请选择经营团队"
            :tdlx="1"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-team-input-popup>
        </u-form-item>
				<!-- <u-form-item
				label="经营公司"
				prop="businessCompanyId"
				:borderBottom="false"
				required>
				<h-select-company-input
					disabled
					style="width: 100%"
					v-model="model.businessCompanyId"
					border="surround"
					placeholder="请选择经营公司"
					suffixIcon="arrow-down-fill"
					:suffixIconStyle="{color: '#B2B2B2'}"
				></h-select-company-input>
              </u-form-item> -->
        <u-form-item label="业绩归属年度" prop="yjgsnd" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.yjgsnd"
            objectField="model.yjgsnd"
            placeholder="请选择业绩归属年度"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="yjgsnd"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="签订单位" prop="qddw" required>
          <h-select-company-input
            style="width: 100%"
            v-model="model.qddw"
            border="surround"
            placeholder="请选择签订单位"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.qddw"
          ></h-select-company-input>
        </u-form-item>
        <u-form-item label="项目承接人" prop="xmcjr" required>
          <h-select-person-input-popup
            v-model="model.xmcjr"
            class="w-100"
            placeholder="请选择项目承接人"
            searchPlaceholder="请输入"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input-popup>
        </u-form-item>
        <u-form-item label="业主单位" prop="yzdw" required>
          <h-select-customer-input
            style="width: 100%"
            v-model="model.yzdw"
            objectField="model.yzdw"
            commercialType="1"
            placeholder="请选择业主单位"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@input="yzdwChange"
          ></h-select-customer-input>
        </u-form-item>
        <u-form-item label="联系人" prop="lxr">
          <h-select-input-tag
            class="w-100"
            v-model="model.lxr"
            objectField="model.lxr"
            placeholder="请选择联系人"
            border="surround"
            :dictName="cust_lxr"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						errorMessage="请选择业主单位"
            @change="lxrChange"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="联系方式" prop="lxfs">
          <u--input v-number-normal placeholder="请输入联系方式" v-model="model.lxfs"></u--input>
        </u-form-item>
        <u-form-item label="签订日期" prop="qdrq">
          <h-time-select
            disabled
            mode="datetime"
            ref="remittanceDate"
            v-model="model.qdrq"
            placeholder="请选择签订日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="履约保证金（元）" prop="bail" required>
          <!-- <u--input v-number-normal placeholder="请输入履约保证金" v-model="model.bail"></u--input> -->
					<h-money-input placeholder="请输入履约保证金" v-model="model.bail"></h-money-input>
        </u-form-item>
				<u-form-item v-if="model.feeType === '1'" label="任务编号" prop="taskId" required>
				<h-select-task-file-input-popup
				    :projectId="model.xmmc"
						:api="erpOmcProjectTaskFinalQueryAllPageList"
            v-model="model.taskId"
            class="w-100"
            :disabled="!model.caId"
            :placeholder="model.projectId ? '请选择任务编号' : '请先选择项目'"
            searchPlaceholder="请输入任务编号"
            label="billNo"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :customParams="{
							distributionType: '!cancel'
              // changeStatus: '!changing',
              // distributionType: 'producting',
            }"
          ></h-select-task-file-input-popup>
        </u-form-item>
        <u-form-item label="是否用印" prop="sfyz" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.sfyz"
            objectField="model.sfyz"
            placeholder="请选择是否用印"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="yn"
						@change="handleRules"
          ></h-select-input-tag>
        </u-form-item>
				<view v-if="model.sfyz=='1'">
					<u-form-item label="用印类型" prop="signSealWay" required>
					  <h-select-input-tag
					    class="w-100"
					    v-model="model.signSealWay"
					    objectField="model.signSealWay"
					    placeholder="请选择用印类型"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
					    border="surround"
					    dictName="seal_way"
							@change="handleSignSealWay"
					  ></h-select-input-tag>
					</u-form-item>
				  <u-form-item label="印章类型" prop="yzlx" required>
				    <!-- <h-select-input-tag-multi-popup
				      class="w-100"
				      v-model="model.yzlx"
				      objectField="model.yzlx"
				      placeholder="请选择印章类型"
				      border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
				      dictName="yzlx_type"
				    ></h-select-input-tag-multi-popup> -->
						<h-dict-multi-select
							v-model="model.yzlx"
							style="width: 100%" 
							placeholder="请选择印章类型"
							dictName="yzlx_type"
							border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{color: '#B2B2B2'}"
						></h-dict-multi-select>
				  </u-form-item>
				  <u-form-item label="用印份数" prop="yyfs" required>
				    <h-number-input placeholder="请输入用印份数" v-model="model.yyfs" :digit="0" :min="1"></h-number-input>
				  </u-form-item>
				</view>
				<u-form-item label="是否存档" prop="sfcd">
				  <h-select-input-tag
						disabled
				    class="w-100"
				    v-model="model.sfcd"
				    objectField="model.sfcd"
				    placeholder="请选择是否存档"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    border="surround"
				    dictName="yn"
						@change="handleRules2"
				  ></h-select-input-tag>
				</u-form-item>
				<view v-if="model.sfcd == '1'">
				  <u-form-item label="合同存档份数" prop="cdfs">
				    <h-number-input placeholder="请输入合同存档份数" disabled v-model="model.cdfs" :digit="0" :min="0"></h-number-input>
				  </u-form-item>
				</view>
				<view v-if="!model.sfyz||model.sfyz=='0'">
					<u-form-item label="合同原件" prop="masterCopy" required>
						<view class="space-y-1" style="width: 100%;">
						  <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
						  <h-upload-file v-model="model.masterCopy" :isIcon="false"></h-upload-file>
						  <file-list v-if="model.masterCopy" v-model="model.masterCopy" :isDelete="true"></file-list>
						</view>
					</u-form-item>
				</view>
        <u-form-item label="关联收款合同" prop="glskht">
					<h-select-input-tag
						class="w-100"
						v-model="model.glskht"
						objectField="model.glskht"
						placeholder="请选择是否关联收款合同"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						dictName="yn"
						@change="glskhtChange"
					></h-select-input-tag>
				</u-form-item>
        <view v-if="model.glskht == 1">
          <u-form-item label="收款合同名称" prop="skhtmc" required>
            <h-select-contract-manager-input-popup
              :muitFlag="false"
              v-model="model.skhtmc"
              htlx="1"
              @change="skhtBack"
              :allList="true"
              :triggerChange="true"
              placeholder="请选择合同名称"
              border="surround"
              style="width: 100%"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
            ></h-select-contract-manager-input-popup>
          </u-form-item>
          <u-form-item label="收款合同额(元)" prop="skhte">
            <u--input type="number" disabled v-number-normal placeholder="请输入收款合同额" v-model="model.skhte" @change="convertMoney1"></u--input>
          </u-form-item>
          <u-form-item label="收款合同额大写" prop="skhtedx">
            <u--input disabled placeholder="请输入收款合同额大写" v-model="model.skhtedx"></u--input>
          </u-form-item>
        </view>
        <u-form-item label="本次合同额(元)" prop="bchte" required>
					<h-money-input placeholder="请输入本次合同额" v-model="model.bchte" @change="convertMoney2"></h-money-input>
        </u-form-item>
        <u-form-item label="本次合同额大写" prop="bchtedx">
          <u--input disabled placeholder="请输入本次合同额大写" v-model="model.bchtedx"></u--input>
        </u-form-item>
        <u-form-item label="服务期限开始日期" prop="fwqx">
          <h-time-select
            mode="date"
            ref="remittanceDate"
            v-model="model.fwqx"
            placeholder="请选择服务期限开始日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						@change="handleBorrowDateChange"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="服务期限结束日期" prop="fwqxEnd">
          <h-time-select
            mode="date"
            ref="remittanceDate"
            v-model="model.fwqxEnd"
            placeholder="请选择服务期限结束日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						:minDate="model.fwqx?(new Date(model.fwqx)).getTime():315504000000"
						@change="predictReturnDateChange"
          ></h-time-select>
        </u-form-item>
      </view>
			
      <view class="basic-style">
        <view class="basic-title basic-border pt-1">受托方(合同乙方)信息</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="addFormA">新增</u-button>
        </view>
				<view v-for="(item, index) in formDataA" :key="index">
					<FormAInfo :isFk="false" :item="item" :index="index" :signSealWay="model.signSealWay" @edit="handleEditFormA" @remove="handleRemoveFormA" @copy="handleCopyFormA" />
				</view>
        <u-popup mode="bottom" :show="showFormModalA">
          <FormA :isFk="false" commercialType="2" ref="dataFormA" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitA" @close="closeFormModalA" />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">委托方(合同甲方)信息</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="addFormB">新增</u-button>
        </view>
				<view v-for="(item, index) in formDataB" :key="index">
					<FormBInfo :isFk="true" commercialType="2" :item="item" :index="index" :signSealWay="model.signSealWay" @edit="handleEditFormB" @remove="handleRemoveFormB" @copy="handleCopyFormB" />
				</view>
        <u-popup mode="bottom" :show="showFormModalB">
          <FormB :isFk="true" ref="dataFormB" :index="index" :signSealWay="model.signSealWay" @submit="handleFormSubmitB" @close="closeFormModalB" />
        </u-popup>
      </view>


      <!-- <view class="basic-style">
        <view class="basic-title basic-border pt-1">任务信息</view>
        <TaskInfo :entities="dataSource2" :newDisabled="true"/>
      </view> -->
			
      <view class="basic-style">
        <view class="basic-title basic-border">收付款计划</view>
				<u-form-item label="是否变更款项信息" prop="fwqxEnd">
				  <h-dict-radio v-model="model.sfbgkxxx" dictName="yn"></h-dict-radio>
				</u-form-item>
        <view class="space-y-1 py-1" v-if="model.sfbgkxxx==1">
          <u-button size="small" type="primary" @click="addFormC">新增</u-button>
        </view>
				<view v-for="(item, index) in formDataC" :key="index">
					<FormCInfo :disabled="model.sfbgkxxx==1" :item="item" :index="index" @edit="handleEditFormC" @remove="handleRemoveFormC" @copy="handleCopyFormC" />
				</view>
        <u-popup mode="bottom" :show="showFormModalC" :closeOnClickOverlay="false">
          <FormC ref="dataFormC" :index="index" @submit="handleFormSubmitC" :htlx="model.htlx" @close="closeFormModalC" />
        </u-popup>
      </view>

      <view class="basic-style">
        <u-form-item label="备注" prop="bz">
          <u--textarea :confirm-type="null" count v-model="model.bz" placeholder="请输入备注" maxlength="500"></u--textarea>
        </u-form-item>
        <u-form-item label="邮寄信息" prop="yjxx">
          <u--textarea :confirm-type="null" count v-model="model.yjxx" placeholder="请输入邮寄信息" maxlength="500"></u--textarea>
        </u-form-item>
      </view>
			
			<view class="basic-style" v-if="model.sfyz == 1">
			  <view class="basic-title basic-border">用印文件<span style="color: #faad14;font-weight: 600">（请上传只需盖章的用印文件！）</span></view>
			  <u-form-item label="用印文件" prop="signFile" required>
					<view class="py-1 space-y-1" style="width: 100%">
						<view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
						<h-upload-file v-model="model.signFile" :fillSize="50" :isIcon="false" :isSingle="true" fileType=".pdf, .PDF, .doc, .docx" fileTypeText="请上传word与pdf格式的文件！"></h-upload-file>
						<file-list v-if="model.signFile" v-model="model.signFile" :isDelete="true"></file-list>
					</view>
				</u-form-item>
			</view>
			
			<view class="basic-style">
			  <view class="basic-title basic-border">合同原件扫描件<span style="color: #faad14;font-weight: 600">（仅合同管理员上传！）</span></view>
			  <view class="py-1 space-y-1" style="width: 100%">
			    <file-list v-model="model.contractOrgFile"></file-list>
			  </view>
			</view>

      <view class="basic-style">
        <view class="basic-title basic-border">相关附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.xgfj" :isIcon="false"></h-upload-file>
          <file-list v-if="model.xgfj" v-model="model.xgfj" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="space-x-1 px-1 btn_position">
				<u-button type="primary" text="保存" :plain="true" :disabled="isSubmit" @click="onDraft"></u-button>
        <u-button type="primary" text="保存提交" :disabled="isSubmit" @click="onSubmit"></u-button>
      </view>
			<view style="height: 100rpx;"></view>
    </u-form>
    
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
		<u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, info,edit } from '@/api/finance/ErpFinanceInvoiceApplicationBillForm'
import { convertCurrency } from '@/utils/utils'
import http from '@/utils/request/index'
import { erpOmcProjectTaskFinalQueryAllPageList } from '@/api/index'

import {
  addInvoiceHandleRecordList,
  erpOmcProjectId,
  relationTaskList,
  erpFinanceProjectDepositBillqueryByEntity,
	erpOmcContractManagerEntrustFinalList,
	erpOmcContractManagerTrusteeFinalList,
	erpOmcContractManagerClassFinalList,
	erpOmcContractManagerPlanFinalList,
  querySupplierByIdserpOmcProjectId,
	erpOmcContractManagerFinalQueryById,
	erpOmcContractManagerEntrustListAll, // 委托方
	erpOmcContractManagerTrusteeListAll, // 受托方
	erpOmcContractManagerPlanListAll, // 收付款计划
	erpOmcCustomerManagerContactId,
} from '@/api/index'
import fileList from '@/pages/synergy/components/fileList.vue'
import PrincipalForm from './components/PrincipalForm.vue'
import PrincipalFormInfo from './components/PrincipalFormInfo.vue'
import FormA from './components/FormA.vue'
import FormAInfo from './components/FormAInfo.vue'
import FormB from './components/FormB.vue'
import FormBInfo from './components/FormBInfo.vue'
import FormC from './components/payFormC.vue'
import FormCInfo from './components/payFormCInfo.vue'
import TaskInfo from './components/TaskInfo.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
export default {
  name: 'ErpOmcPayContractManagerForm',
  components: { fileList, PrincipalForm, PrincipalFormInfo, FormA, FormAInfo, FormB, FormBInfo, FormC, FormCInfo, TaskInfo,ProcessNodeConfiguration },
  data() {
    return {
      flag: false,
      cust_lxr: '',
      backUpApplicant: '',
      backUpTeamId: '',
      isReset: false,
      resetKey: '',
      index: null,
      loading: false,
      id: '',
			erpOmcProjectTaskFinalQueryAllPageList,
      dataSource2: [],
      basicFormA: {},
      basicFormB: {},
      basicFormC: {},
      showFormModalA: false,
      showFormModalB: false,
      showFormModalC: false,
      formDataA: [],
      formDataB: [],
      formDataC: [],
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        htbh: '',
        proposer: '',
        proposerDeptId: '',
        createTime: '',
				applyTeam: '',
        // 基本信息 - 非公用
        masterCopy: null,
				caId: '',
				feeType: '',
				isCategoryType: '',
        bchte: '',
				htlx: 2,
				lx:2,
				bglx: '',
				sfbgkxxx:'0',//是否变更款项信息
				signSealWay: '', // 用印类型
        // 附件
        xgfj: null,
				glskht: '0',
				sfyz: '',
				signFile: null // 用印文件
      },
      rules: {
				htbh: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
        bchte: [{ required: true, message: '请输入本次合同额!' }],
				caId: [{ required: true, message: '请选择合同编号!' }],
				bglx: [{ required: true, message: '请选择变更类型!' }],
        htlx: [{ required: true, message: '请选择合同类型!' }],
        htmc: [{ required: true, message: '请输入合同名称!' }],
				applyTeam: [{ required: true, message: '请选择申请人所属团队!' }],
        xmmc: [{ required: true, message: '请选择项目名称!' }],
        jytd: [{ required: true, message: '请选择经营团队!' }],
        yjgsnd: [{ required: true, message: '请选择业绩归属年度!' }],
        qddw: [{ required: true, message: '请选择签订单位!' }],
        bail: [{ required: true, message: '请输入履约保证金!' }],
        xmcjr: [{ required: true, message: '请选择项目承接人!' }],
        yzdw: [{ required: true, message: '请选择业主单位!' }],
        // yzlx: [{ required: true, message: '请选择印章类型!' }],
        // yyfs: [
        //   { required: true, message: '请填写用印份数!', trigger: 'blur' },
        //   { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
        // ],
        lxfs: [
          { required: false },
          { pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!',trigger: ['blur','change'] },
        ],
        sfyz: [{ required: true, message: '请选择是否用印!' }],
				signSealWay: [{ required: true, message: '请选择用印类型!' }],
				signFile: [{ required: true, message: '请上传用印文件!' }],
				// sfcd: [{ required: true, message: '请选择是否存档!' }],
				glskht: [{ required: true, message: '请选择是否关联收款合同!' }],
        feeType: [{ required: true, message: '请选择费用类型!' }],
        isCategoryType: [{ required: true, message: '请选择是否采购类!' }],
      },
			isSubmit:false,
			projectName: '',
			// 代码生成后需手动设置流程编码
			flowCode: 'dev_erp_omc_contract_manager_003',
			formUrl: 'erp/omc/contractmanager/modules/ErpOmcPayContractManagerForm',
			formUrlMobile: '/pages/synergy/erpOmcPayContractManagerList',
			beanName: 'erpOmcPaymentContractManagerServiceImpl',
			processId: '1557651427069722625',
    }
  },
  onLoad({ id }) {
    this.id = id || ''
		if (this.id) {
		  this.initInfo()
		} else {
		  this.initForm()
		  this.initBillNo()
		}
  },
  computed: {
    ...mapState(['userInfo']),
    formTotal() {
      return this.formDataA.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
    },
  },
  methods: {

		changeBusinessCompany(val){
			this.model.businessCompanyId = val.belongCompanyId
		},

		// 选择联系人
		lxrChange(val) {
			erpOmcCustomerManagerContactId({ id: val }).then((res) => {
				if (res.success) {
					let data = res.result.records || res.result
					this.$set(this.model, 'lxr', val)
					this.$set(this.model, 'lxfs', data.lxfs)
				}
			})
		},
		glskhtChange(val){
			if (val == '1') {
				this.$set(this.rules, 'skhtmc', [{ required: true, message: '请输入收款合同名称!' }]);
			} else {
				this.$set(this.model, 'skhtmc', '');
				this.$set(this.model, 'skhte', '');
				this.$set(this.model, 'skhtedx', '');
				this.$delete(this.rules, 'skhtmc');
			}
		},
		handleBorrowDateChange(date, dateStr) {
		  this.$set(this.model, 'fwqxEnd', undefined)
		  this.fwqxEnd = undefined
		},
		predictReturnDateChange (date, dateStr) {
			if (!this.model.fwqx) {
				return false
			}
			let isBefore = moment(this.model.fwqx).isBefore(this.model.fwqxEnd)
			if (!isBefore) {
				const format = 'YYYY-MM-DD'
				const fwqx = moment(this.model.fwqx, format)
				const fwqxEnd = moment(this.model.fwqxEnd, format)
				if (fwqx.isSame(fwqxEnd)) {
					return false
				}
				this.$u.toast('服务期限结束时间必须大于开始时间！')
				this.$nextTick(() => {
					this.model.fwqxEnd = null
				})
			}
		},
		// 选择合同编号
		htbhChange(val) {
			erpOmcContractManagerFinalQueryById({ id: val.id }).then((res) => {
		        if (res.success) {
					let data = res.result.records || res.result
					// debugger;
					this.$set(this.model, 'caId', val.id)
					this.$set(this.model, 'bpmBizTitle', data.htmc) // 标题
					this.$set(this.model, 'htmc', data.htmc) // 合同名称
					this.$set(this.model, 'htlx', data.htlx) // 合同类型
					this.$set(this.model, 'applyTeam', data.applyTeam) // 申请人所属团队
					this.$set(this.model, 'applyTeam', data.applyTeam || '') // 申请人所属团队
					this.$set(this.model, 'contractOrgFile', data.contractOrgFile || '') // 合同原件扫描
					this.$set(this.model, 'taskId', data.taskId) // 
					
					// fix:BUG#4955 合同变更-当合同类型为付款合同，带出的委托方、受托方信息错误 start
					
					// fix:BUG#4955 合同变更-当合同类型为付款合同，带出的委托方、受托方信息错误 end
					this.$set(this.model, 'xmmc', data.xmmc) // 项目名称
					this.$set(this.model, 'jytd', data.jytd) // 经营团队
					this.$set(this.model, 'businessCompanyId', data.businessCompanyId) // 经营公司
					this.$set(this.model, 'yjgsnd', data.yjgsnd)// 业绩归属年度
					this.$set(this.model, 'qddw', data.qddw) // 签订单位
					this.$set(this.model, 'xmcjr', data.xmcjr) // 项目承认人
					this.$set(this.model, 'yzdw', data.yzdw)// 业主单位
					this.$set(this.model, 'lxr', data.lxr)// 联系人
					this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
					this.$set(this.model, 'lxfs', data.lxfs) // 联系方式
					this.$set(this.model, 'qdrq', data.qdrq)// 签订日期
					this.$set(this.model, 'sfyz', String(data.sfyz))// 是否用印
					this.$set(this.model, 'signSealWay', data.signSealWay)// 用印类型
					this.$set(this.model, 'signFile', data.signFile)// 用印文件
					this.$set(this.model, 'sfcd', data.sfcd)// 是否存档
					this.$set(this.model, 'yzlx', data.yzlx) // 印章类型
					this.$set(this.model, 'yyfs', data.yyfs)// 用印份数
					this.$set(this.model, 'cdfs', data.cdfs) // 合同存档份数
					
					this.$set(this.model, 'glskht', data.glskht) // 关联收款合同
					this.glskhtChange(data.glskht)
					this.$set(this.model, 'skhtmc', data.skhtmc) // 收款合同名称
					// this.$set(this.model, 'jf', data.yzdw) // 甲方
					this.$set(this.model, 'jf', data.jf)// 甲方
					this.$set(this.model, 'yf', data.yf)// 已方
					// this.$set(this.model, 'yf', data.qddw) // 已方
					this.$set(this.model, 'skhte', String(data.skhte))// 收款合同额
					this.$set(this.model, 'skhtedx', data.skhtedx)// 收款合同额大写
					this.$set(this.model, 'feeType', data.feeType)// 费用类型
					let bchte = data.bchte;
					
					this.$set(this.model, 'bchte', bchte)
					this.$set(this.model, 'bchtedx', data.bchtedx)
					this.$set(this.model, 'fwqx', data.fwqx)
					this.$set(this.model, 'fwqxEnd', data.fwqxEnd)
					// 服务期限
					if (!!this.model.fwqx && !!this.model.fwqxEnd) {
						this.createTime = []
						this.createTime.push(this.model.fwqx)
						this.createTime.push(this.model.fwqxEnd)
					} else {
						this.createTime = []
					}
					this.$set(this.model, 'bz', data.bz) // 备注
					this.$set(this.model, 'yjxx', data.yjxx) // 邮寄信息
					this.$set(this.model, 'xgfj', data.xgfj) // 相关附件
					this.$set(this.model, 'htbh', data.htbh) // 合同编号
					this.$set(this.model, 'xmbh', data.xmbh) // 合同编号
		
					this.$set(this.model, 'isCategoryType', data.isCategoryType) // 是否采购类
					this.$set(this.model, 'provisionType', data.provisionType) // 采购类型
					this.$set(this.model, 'calibrationId', data.calibrationId) // 定标结果确认单
					this.$set(this.model, 'purchaseApplyId', data.purchaseApplyId) // 采购申请单
					this.$set(this.model, 'invitationId', data.invitationId) // 招标采购申请单
					this.handleChangeCategory(data.isCategoryType)
					if (data.isCategoryType == '1') {
						this.handleProvisionType(data.provisionType)
					}
					// this.$set(this.model, 'bglx', data.bglx)
					this.$set(this.model, 'sfbgkxx', data.sfbgkxx)
					// this.$set(this.model, 'proposer', data.proposer)
					// this.$set(this.model, 'proposerDeptId', data.proposerDeptId)
					// this.$set(this, 'isFkht', data.htlx != '1')
					this.$set(this.model, 'involveMultiple', data.involveMultiple)
					// this.$set(this, 'involveMultipleFlag', data.involveMultiple == 1)
					this.$set(this.model, 'masterCopy', data.masterCopy) // 合同原件
					this.$set(this.model, 'bail', '0.00')
					Object.keys(this.model).map(key => {
						if(typeof this.model[key] == 'number'){
							this.model[key] = String(this.model[key])
						}
					})
					this.handleRules()
					this.handleRules2()
					// 收款计划
					erpOmcContractManagerPlanFinalList({ mainId: val.id }).then((res) => {
						if (res.success) {
						  this.formDataC = res.result.records || res.result
						  if (this.formDataC.length > 0) {
							this.formDataC.forEach((item, index) => {
							  item.finalId = item.id
							})
						  }
						}
					})
					var params = {
						preProjectId: data.xmmc,
						feeCategory: '2',
						bpmStatus: '3'
					}
					// 查看项目保证金
					erpFinanceProjectDepositBillqueryByEntity( params).then((res) => {
						if (res.success) {
						  let data = res.result.records || res.result
						  this.$set(this.model, 'bail', data.remittanceAmount)
						}
					})
					// 任务信息
					// erpOmcContractManagerClassFinalList( { mainId: val.id }).then((res) => {
					// 	if (res.success) {
					// 	  this.dataSource2 = res.result.records || res.result
					// 	  this.dataSource2.forEach((item, index) => {
					// 		item.finalId = item.id
					// 		if (this.model.bchte && item.htzb) {
					// 		  let amount = this.model.bchte * item.htzb / 100
					// 		  item.fphte = Math.round((amount + Number.EPSILON) * 100) / 100;
					// 		}
					// 	  })
					// 	}
					// })
					// 项目赋值
					erpOmcProjectId( { id: data.xmmc }).then((res) => {
						if (res.success) {
						  let data = res.result.records || res.result
						  this.$set(this, 'projectName', data.projectName); // 项目名称
						}
					}),
					// 受托方信息
					erpOmcContractManagerTrusteeFinalList( { mainId: val.id }).then((res) => {
						if (res.success) {
							this.formDataB = res.result.records || res.result
							this.formDataB.forEach((item, index) => {
							  item.finalId = item.id
							})
						}
					}),
					// 委托方信息
					erpOmcContractManagerEntrustFinalList( { mainId: val.id }).then((res) => {
						if (res.success) {
							this.formDataA = res.result.records || res.result
							this.formDataA.forEach((item, index) => {
							  item.finalId = item.id
							})
						}
					})
		    }
		  })
		},
		yzdwChange() {
			this.$set(this.model, 'lxr', undefined);
			this.$set(this.model, 'lxfs', undefined);
			// this.cust_lxr = erp_omc_customer_manager_contact,lxr,id;
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
			// this.$set(this.model, 'lxr', undefined);
			// this.$set(this.model, 'lxfs', undefined);
		},
		handleProvisionType(val){
			if (val == '1') {
				this.$set(this.rules, 'calibrationId', [{ required: true, message: '请选择定标结果确认单!' }]);
				//清除采购申请单数据及校验
				this.$set(this.model, 'purchaseApplyId', null);
				this.$delete(this.rules, 'purchaseApplyId');
				//清除招标采购申请单数据及校验
				this.$set(this.model, 'invitationId', null);
				this.$delete(this.rules, 'invitationId');
			} else if (val == '2') {
				this.$set(this.rules, 'purchaseApplyId', [{ required: true, message: '请选择采购申请单!' }]);
				//清除定标结果确认单数据及校验
				this.$set(this.model, 'calibrationId', null);
				this.$delete(this.rules, 'calibrationId');
				//清除招标采购申请单数据及校验
				this.$set(this.model, 'invitationId', null);
				this.$delete(this.rules, 'invitationId');
			} else if (val == '3'){
				this.$set(this.rules, 'invitationId', [{ required: true, message: '请选择招标采购申请单!' }]);
				this.$set(this.model, 'calibrationId', null);
				this.$delete(this.rules, 'calibrationId');
				this.$set(this.model, 'purchaseApplyId', null);
				this.$delete(this.rules, 'purchaseApplyId');
			}else {
				//清除采购申请单数据及校验
				this.$set(this.model, 'purchaseApplyId', null);
				this.$delete(this.rules, 'purchaseApplyId');
				//清除招标采购申请单数据及校验
				this.$set(this.model, 'invitationId', null);
				this.$delete(this.rules, 'invitationId');
				//清除定标结果确认单数据及校验
				this.$set(this.model, 'calibrationId', null);
				this.$delete(this.rules, 'calibrationId');
			}
		},
		handleChangeFeeType(val){
			if(this.model.feeType==='2'){// 经营费用
				this.$set(this.model,'jytd',null)
				this.$set(this.model,'businessCompanyId',null)
				this.$set(this.model, 'taskId', '')
				this.$set(this.rules,'jytd',[{ required: true, message: '请输入费用所属团队!' }])
			}else {// 其他
				// 如果有项目自动带出项目中的经营团队
				if(this.model.xmmc){
					erpOmcProjectId({ id: this.model.xmmc }).then((res) => {
						if (res.success) {
							let data = res.result.records || res.result
							this.$set(this.model, 'jytd', data.oldTeamId?data.oldTeamId:data.teamName) // 经营团队
							this.$set(this.model, 'businessCompanyId', data.businessCompanyId) // 经营公司
						}
					})
				}
				this.$set(this.rules,'jytd',[{ required: true, message: '请输入经营团队!' }])
			}
		},
		handleRules(val){
			if(this.model.sfyz == '1'){
				this.$set(this.rules,'yzlx',[{ required: true, message: '请选择印章类型!' }])
				this.$set(this.rules,'yyfs',[
		      { required: true, message: '请输入用印份数!', trigger: 'blur' },
		      { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
		    ])
				this.$delete(this.rules,'masterCopy')
				this.$set(this.model,'masterCopy','')
			} else {
				this.$delete(this.rules,'yzlx')
				this.$delete(this.rules,'yyfs')
				this.$set(this.model,'yzlx','')
				this.$set(this.model,'yyfs','')
				this.$set(this.rules,'masterCopy',[{ required: true, message: '请上传合同原件!' }])
				this.$set(this.model, 'signSealWay', null) // 置空电子签章
			}
			if (val == 0) {
				if (this.formDataB && this.formDataB.length) {
					this.formDataB.forEach(value => {
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
				if (this.formDataA && this.formDataA.length) {
					this.formDataA.forEach(value => {
						value.isSignSeal = '0'
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
			}
			
		},
		// 点击选择用印类型
		handleSignSealWay (val) {
			if (val == 'online') {
				if (this.formDataA && this.formDataA.length) {
					this.formDataA.forEach(value => {
						value.isSignSeal = 0
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
			} else {
				if (this.formDataB && this.formDataB.length) {
					this.formDataB.forEach(value => {
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
				if (this.formDataA && this.formDataA.length) {
					this.formDataA.forEach(value => {
						value.isSignSeal = 0
						value.psnName = null
						value.psnMobile = null
						return value
					})
				}
			}
		},
		handleRules2(val){
			if(this.model.sfcd == '1'){
				// this.$set(this.rules,'cdfs',[
		  //     { required: true, message: '请输入合同存档份数!', trigger: 'blur' }
		  //   ])
			} else {
				// this.$delete(this.rules,'cdfs')
				this.$set(this.model,'cdfs',null)
			}
		},
    skhtBack(item) {
			if(!item){
				this.$set(this.model, 'jf', undefined)
				this.$set(this.model, 'skhte', undefined)
				this.$set(this.model, 'skhtedx', undefined)
			} else {
				this.$set(this.model, 'jf', item.qddw)
				this.$set(this.model, 'skhte', item.bchte)
				this.$set(this.model, 'skhtedx', item.bchtedx)
			}
    },
    handleChangeCategory(val) {
      if (val == '1') {
        this.$set(this.rules, 'provisionType', [{ required: true, message: '请选择采购类型!' }])
      } else {
        this.$set(this.model, 'provisionType', null)
        this.$delete(this.rules, 'provisionType')
        this.$set(this.model, 'purchaseApplyId', null)
        this.$delete(this.rules, 'purchaseApplyId')
        this.$set(this.model, 'calibrationId', null)
        this.$delete(this.rules, 'calibrationId')
      }
    },
    convertMoney1() {
      let money = this.model.skhte
      this.$set(this.model, 'skhtedx', convertCurrency(money))
    },
    convertMoney2() {
      let money = this.model.bchte
      this.$set(this.model, 'bchtedx', convertCurrency(money))
      // this.dataSource2.forEach((item, index) => {
      //   //  item.finalId = item.id
      //   if (this.model.bchte && item.htzb) {
      //     // item.fphte = this.model.bchte * item.htzb / 100
      //     let amount = (item.fphte / this.model.bchte) * 100
      //     item.htzb = Math.round((amount + Number.EPSILON) * 100) / 100
      //   }
      // })
    },
    xmmcChange({ id: val }) {
      erpOmcProjectId({ id: val }).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$set(this.model, 'calibrationId', null) // 定标结果确认单
          this.$set(this.model, 'yzdw', data.ownerUnit) // 业主单位
          this.$set(this.model, 'bail', '0')
          // debugger;
          // this.model.lxdh = data.lxfs;
          // 迭代16.7 选择灰色类型的团队不用带出团队
          if(this.model.feeType!=='2'){
						this.$set(this.model, 'jytd', data.oldTeamId?data.oldTeamId:data.teamName) // 经营团队
						this.$set(this.model, 'businessCompanyId', data.businessCompanyId) // 经营公司
          }else {
            this.$set(this.model, 'jytd', null) // 经营团队
            this.$set(this.model, 'businessCompanyId', null) // 经营公司
          }
          this.$set(this.model, 'xmbh', data.finalNo) // 项目编号
          this.$set(this.model, 'yjgsnd', data.year) // 业绩归属年度
          this.$set(this.model, 'qddw', data.signUnit) // 签定单位
          this.$set(this.model, 'xmcjr', data.undertaker) // 项目承接人
          this.$set(this.model, 'lxfs', data.contactTel) // 联系方式
          this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
          this.$set(this.model, 'lxr', data.contacts) // 联系人
          this.projectName = data.projectName
          // 任务信息
          // relationTaskList({ projectId: data.id }).then((res) => {
          //   this.dataSource2 = []
          //   if (res.success) {
          //     let data = res.result.records || res.result
          //     for (let i = 0; i < data.length; i++) {
          //       let d = {
          //         id: data[i].id,
          //         ywfl: data[i].categoryCode,
          //         ywmc: data[i].categoryName,
          //         htzb: data[i].contractRate,
          //         fphte: data[i].contractAmount,
          //         sctd: data[i].productTeam,
          //         sctd_dictText: data[i].productTeam_dictText,
          //         tdfzr: data[i].teamLeader,
          //         tdfzr_dictText: data[i].teamLeader_dictText,
          //         projectTaskId: data[i].id,
          //       }
          //       let index = this.dataSource2.findIndex((item) => item.ywfl == d.ywfl)
          //       if (index > -1) {
          //         this.dataSource2.splice(index, 1, d)
          //       } else {
          //         this.dataSource2.push(d)
          //       }
          //     }
          //   }
          // })
          var params = {
            preProjectId: data.id,
            feeCategory: '2',
            bpmStatus: '3',
          }
          // 查看项目保证金
          erpFinanceProjectDepositBillqueryByEntity(params).then((res) => {
            if (res.success) {
              let data = res.result.records || res.result
              this.$set(this.model, 'bail', data.remittanceAmount)
            }
          })
        }
      })
    },
    handleCopyFormA([item, index]) {
      this.formDataA.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditFormA([item, index]) {
      this.basicFormA = { ...item }
      this.index = index
      this.showFormModalA = true
			this.$nextTick(() => {
				this.openFormModalA()
			})
    },
    handleRemoveFormA(item) {
      this.formDataA = this.formDataA.filter((i) => i !== item)
    },
    closeFormModalA() {
      this.$refs.dataFormA.reset()
      this.basicFormA = {}
      this.index = null
			this.showFormModalA = false
    },
    openFormModalA() {
      this.$refs.dataFormA.basicForm = Object.assign({},this.basicFormA)
    },
    handleCopyFormB([item, index]) {
      this.formDataB.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    addFormA() {
      this.index = null
			this.basicFormA = {}
      this.showFormModalA = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmitA([data, index]) {
      this.showFormModalA = false
      if (typeof index === 'number') {
        this.$set(this.formDataA, index, data)
      } else {
        this.formDataA.push(data)
      }
      // this.initBuyerInfo()
    },
    handleEditFormB([item, index]) {
      this.basicFormB = { ...item }
      this.index = index
      this.showFormModalB = true
			this.$nextTick(() => {
				this.openFormModalB()
			})
    },
    handleRemoveFormB(item) {
      this.formDataB = this.formDataB.filter((i) => i !== item)
    },
    closeFormModalB() {
      this.$refs.dataFormB.reset()
      this.basicFormB = {}
      this.index = null
			this.showFormModalB = false
    },
    openFormModalB() {
      this.$refs.dataFormB.basicForm = Object.assign({},this.basicFormB)
    },
    addFormB() {
      this.index = null
			this.basicFormB = {}
      this.showFormModalB = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmitB([data, index]) {
      this.showFormModalB = false
      if (typeof index === 'number') {
        this.$set(this.formDataB, index, data)
      } else {
        this.formDataB.push(data)
      }
      // this.initBuyerInfo()
    },
    handleEditFormC([item, index]) {
      this.basicFormC = { ...item }
      this.index = index
      this.showFormModalC = true
			this.$nextTick(() => {
				this.openFormModalC()
			})
    },
    handleRemoveFormC(item) {
      this.formDataC = this.formDataC.filter((i) => i !== item)
    },
    closeFormModalC() {
      this.$refs.dataFormC.reset()
      this.basicFormC = {}
      this.index = null
			this.showFormModalC = false
    },
    openFormModalC() {
      this.$refs.dataFormC.basicForm = Object.assign({},this.basicFormC)
    },
    handleCopyFormC([item, index]) {
      this.formDataC.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    addFormC() {
      this.index = null
			this.basicFormC = {}
      this.showFormModalC = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmitC([data, index]) {
      this.showFormModalC = false
      if (typeof index === 'number') {
        this.$set(this.formDataC, index, data)
      } else {
        this.formDataC.push(data)
      }
      // this.initBuyerInfo()
    },
    // queryBillByProject(item) {
    //   this.$set(this.model, 'applicant', item.signUnit)
    //   this.$set(this.model, 'projectYear', item.year)
    //   this.$set(this.model, 'projectBusiTeamId', item.teamName)
    //   queryBillByProject({ projectId: this.model.projectId }).then((res) => {
    //     if (res.success) {
    //       let data = res.result
    //       if (data) {
    //         this.$set(this.model, 'projectPaidTotalAmount', data.projectTotalAmount)
    //         this.projectPaidTotalAmount = data.projectTotalAmount
    //         this.constructTotalAmount = data.constructAmount
    //       }
    //     }
    //   })
    // },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ prefix: 'HT', subSystemCode: '05' })
      this.model.htbh = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.htbh //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
			this.model = Object.assign({}, data)
			this.$set(this.model, 'skhtedx', convertCurrency(this.model.skhte))
			this.$set(this.model, 'bchtedx', convertCurrency(this.model.bchte))
			this.cust_lxr = 'erp_omc_customer_manager_contact,lxr,id,del_flag=0 and main_id=\'' + this.model.yzdw + '\'';
			if (this.model && this.model.htlx) {
				if (this.model.isCategoryType) {
					this.handleChangeCategory(this.model.isCategoryType)
					if (this.model.provisionType) {
						this.handleProvisionType(this.model.provisionType)
					}
				}
				this.contractType = this.model.htlx
				this.projectName = this.model.xmmc_dictText
			}
			if(!this.model.skhtmc){
				this.model.skhte = undefined
			}
			this.$set(this.model,'bail',(data.bail === null ||data.bail === undefined || data.bail === '') ?'':String(data.bail))
			this.$set(this.model,'sfyz',String(data.sfyz))
      const resA = await erpOmcContractManagerEntrustListAll({ mainId: this.model.id })
      this.formDataA = resA.result.records || resA.result
      const resB = await erpOmcContractManagerTrusteeListAll({ mainId: this.model.id })
      this.formDataB = resB.result.records || resB.result
      const resC = await erpOmcContractManagerPlanListAll({ mainId: this.model.id })
      this.formDataC = resC.result.records || resC.result
			this.glskhtChange(this.model.glskht)
      this.handleRules()
      this.handleRules2()
    },
    valdateContractMoney() {
      let planSum = 0
      this.formDataC.forEach((data) => {
        planSum += Number(data.je)
      })
      // 迭代11 TASK#3763 2.收付款计划栏金额与合同总金额不对等时不可以发起，需要校验核对收付款计划金额和合同总金额
      if (Number(this.model.bchte).toFixed(2) != planSum.toFixed(2)) {
        this.$u.toast('计划总金额与合同金额不对等!')
        return false
      }
      // 付款合同的本次合同额应该只是对外的任务的金额，不能校验本次合同额等于所有任务的总额
      if (this.model.htlx === 1 || this.model.htlx === '1') {
        let total = 0
        // this.dataSource2.forEach((val) => {
        //   total += val.fphte
        // })
        if (total.toFixed(2) != this.model.bchte.toFixed(2)) {
          this.$u.toast('分配项金额和本次合同额不相等，请重新填写')
          return false
        }
      }
      return true
    },
    // 校验委托方和受托方子表数据合法性 委托方和受托方列表需要校验两个分别必须至少有一条数据 是否为收付款单位有各且仅有一个
    validateClientDetailAndTrusteeDetail() {
      if (!this.formDataA.length) {
        this.$u.toast('请填写受托方信息!')
        return false
      }
      if (!this.formDataB.length) {
        this.$u.toast('请填写委托方信息!')
        return false
      }
      const hasFkList = this.formDataB.filter((i) => i.isFk == '1')
      if (hasFkList.length != 1) {
        this.$u.toast('委托方有且仅有一个是付款单位!')
        return false
      }
			// 判断当选择是否用印为是且用印类型是电子签章的时候判断是否填写了盖章人信息和联系方式信息
			let psnName = this.formDataB.filter(item => !item.psnName);
			let psnMobile = this.formDataB.filter(item => !item.psnMobile);
			if (this.model.sfyz && this.model.sfyz == 1 && this.model.signSealWay == 'online') {
				// 当主表选择了电子签章
				if (psnName.length || psnMobile.length) {
					this.$u.toast('请填写委托方联系人和联系方式!')
				return false;
				}
			}
      const hasSkList = this.formDataA.filter((i) => i.isSk == '1')
      if (hasSkList.length != 1) {
        this.$u.toast('受托方有且仅有一个是收款单位!')
        return false
      }
			// 判断当选择是否用印为是且用印类型是电子签章的时候判断是否填写了盖章人信息和联系方式信息
			// let psnName = this.formDataA.filter(item => item.psnName);
			// let psnMobile = this.formDataA.filter(item => item.psnMobile);
			if (this.model.sfyz && this.model.sfyz == 1 && this.model.signSealWay == 'online') {
				// 当主表选择了电子签章
				for (var i = 0; i < this.formDataA.length; i++) {
					if (this.formDataA[i].isSignSeal && this.formDataA[i].isSignSeal == 1) {
						if (!this.formDataA[i].psnName || !this.formDataA[i].psnMobile) {
							this.$u.toast('请填写受托方联系人和联系方式!')
							return
						}
					}
				}
			}
      return true
    },
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		},
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (!this.valdateContractMoney()) {
          return Promise.reject('金额校验失败')
        }
        if (!this.validateClientDetailAndTrusteeDetail()) {
          return Promise.reject('信息校验失败')
        }
        return Promise.resolve()
      })
    },
		//处理首付款计划，新增sortOrder字段
		handelPlanList(list){
			for (let i = 0; i < list.length; i++) {
				list[i].sortOrder=i;
			}
			return list;
		},
    async onSubmit() {
      await this.validateForm()
			let url = ''
			let method = ''
			this.model.bpmBizTitle =  (this.projectName? this.projectName+ ' - ':'') + this.userInfo?.employee?.name + '-' + this.model.htbh
			if (this.id) {
				url = await edit
				 method = 'put'
			} else {
				url = await add
				method = 'post'
			}
			this.isSubmit = true
			try {
				
				const response = await url({
					...this.model,
					entrustList: this.formDataA,
					trusteeList: this.formDataB,
					planList: this.handelPlanList(this.formDataC),
					// classList: this.dataSource2,
				})
				this.$u.toast(response.message)
				if (response.success) {
          const verifyId = method === 'put' ? this.id : response.result;
					const result = await http.get('/api/erp/omc/contractmanager/erpOmcContractManager/verify', { id: verifyId})
          if(!result.success) {
						  uni.showToast({title: result.message,icon: 'none'})
							setTimeout(()=>{
                uni.navigateBack()
              },2000)
							return
					}
					if (this.model.id) {
						await this.getProcessList(this.model.id)
					} else {
						// 判断添加的时候是否有返回id值
						if (response.result) {
							await this.getProcessList(response.result)
						}
					}
				}
			}  finally {
			// this.loading = false
			}
    },
    async onDraft() {
      // await this.validateForm()
			let url = ''
			this.model.bpmBizTitle =  (this.projectName? this.projectName+ ' - ':'') + this.userInfo?.employee?.name + '-' + this.model.htbh
			if (this.id) {
				url = await edit
			} else {
				url = await add
			}
			this.isSubmit = true
			try {
			  const response = await url({
			    ...this.model,
			    entrustList: this.formDataA,
			    trusteeList: this.formDataB,
			    planList: this.handelPlanList(this.formDataC),
			    // classList: this.dataSource2,
			  })
			  if (response.success) {
			   this.$refs.uToast.show({
			    	message: response.message,
			    	type: 'default',
			    	complete () {
			    		this.isSubmit = false
			    		if (getCurrentPages().length > 1) {
			    			uni.navigateBack()
			    		} else {
			    			uni.reLaunch({
			    				url: '/pages/home/home'
			    			})
			    		}
			    		
			    	}
			    })
			  }
			} finally {
			  // this.loading = false
			}
    },
  }
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
